package cn.edu.hit.core.db;

import cn.edu.hit.core.Document;
import cn.edu.hit.core.conf.ConfigureLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ServiceLoader;
import java.util.stream.StreamSupport;

public final class DataConnectionLoader {
    static Logger logger = LoggerFactory.getLogger(DataConnectionLoader.class);

    public static DataConnection getInstance() {
        ServiceLoader<DataConnection> loader = ServiceLoader.load(DataConnection.class);

        ConfigureLoader configureLoader = ConfigureLoader.getInstance();
        Document configure = configureLoader.getBaseConfigure();

        return StreamSupport.stream(loader.spliterator(), false)
                .filter(conn -> {
                    ;
                    boolean result = conn.connect(configure);
                    if (result) {
                        logger.info("配置读取成功");
                    }
                    return result;
                })
                .findAny()
                .orElse(new EmptyDataConnection());
    }
}
